using BlogApi.Common;
using BlogApi.Dtos;
using BlogApi.Interfaces;
using BlogApi.Models;
using Microsoft.AspNetCore.Mvc;

namespace BlogApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BlogController : ControllerBase
{
    private readonly IBlogRepository<Blog> _blogRepository;
    public BlogController(IBlogRepository<Blog> blogRepository)
    {
        _blogRepository = blogRepository;
    }

    [HttpGet]
    public IActionResult GetAllBlogs()
    {
        var list = _blogRepository.GetAllBlogs();
        if (list.Count != 0)
        {
            return Ok(ApiResponse<List<Blog>>.Success(list));
        }
        else
        {
            return NotFound(ApiResponse<string>.Fail(4040, "暂无数据"));
        }
    }

    [HttpPost]
    public IActionResult AddBlog(BlogDto blogDto)
    {
        var blog = new Blog(blogDto.Title, blogDto.Author);
        _blogRepository.AddBlog(blog);
        return Ok(ApiResponse<BlogDto>.Success(blogDto, "新增成功"));
    }

    [HttpPut("{id}")]
    public IActionResult EditBlog(Guid id, BlogDto blogDto)
    {
        var blog = _blogRepository.GetById(id);
        if (blog == null)
        {
            return NotFound(ApiResponse<string>.Fail(5000, "查无此博,修改失败"));
        }
        blog.Title = blogDto.Title;
        blog.Author = blogDto.Author;
        blog.UpdatedAt = DateTime.Now;
        _blogRepository.EditBlog(blog);
        return Ok(ApiResponse<BlogDto>.Success(blogDto, "修改成功"));
    }

    [HttpDelete("{id}")]
    public IActionResult DelBlog(Guid id)
    {
        var blog = _blogRepository.GetById(id);
        if (blog == null)
        {
            return NotFound(ApiResponse<string>.Fail(5000, "查无此博,删除失败"));
        }
        var obj = _blogRepository.DelById(blog);
        return Ok(ApiResponse<Blog>.Success(obj, "删除成功"));
    }

}